import numpy as np
import math
import logging
from collections import deque
from typing import Dict, List, Tuple, Optional
from scipy import signal
from scipy.stats import zscore
import warnings
import sys
import os

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
if project_root not in sys.path:
    sys.path.append(project_root)

from response.BrainWaveResult import BrainWaveResult
from exception.base_exceptions import FilterException, SignalProcessingException
from exception.exception_handler import global_exception_handler
warnings.filterwarnings('ignore')

logger = logging.getLogger(__name__)

class AdvancedSignalFilter:
    """
    基于信号处理和生理学原理的高级脑电信号异常值检测与过滤服务
    
    主要特征：
    1. 信号连续性检测 - 基于生理学原理，脑电信号应该连续变化
    2. 频域特征分析 - 检测非生理性的频谱异常
    3. 多波段相关性验证 - 利用不同波段间的生理学关联
    4. 自适应阈值调整 - 根据个体差异动态调整检测参数
    """
    
    def __init__(self, sampling_rate: float = 512.0, window_size: int = 20):
        """
        初始化高级信号过滤器
        
        Args:
            sampling_rate: 采样率 (Hz)
            window_size: 分析窗口大小
        """
        self.sampling_rate = sampling_rate
        self.window_size = window_size
        
        # 冷启动改进功能
        self.cold_start_count = 0
        self.cold_start_threshold = 5  # 前5个数据点为冷启动期
        
        # 统计信息
        self.global_stats = {
            'total_processed': 0,
            'anomalies_detected': 0,
            'replacements_made': 0
        }
        
        # 状态转换检测相关
        self.state_transition_detector = {
            'recent_patterns': deque(maxlen=10),  # 存储最近的频域模式
            'transition_threshold': 50.0,  # 状态转换检测阈值（降低以更容易检测转换）
            'transition_buffer_size': 5,  # 转换缓冲期大小（增加缓冲期）
            'in_transition': False,  # 是否处于转换期
            'transition_counter': 0  # 转换期计数器
        }
        
        # 各波段的生理学参数 - 8频域增强版本
        self.band_configs = {
            'delta': {
                'freq_range': (0.5, 4),   # Delta波段：0.5-4Hz
                'max_change_rate': 1.5,   # 最大变化率 (150%/sample) - 冷启动期更宽松
                'physiological_range': (0, 300000),  # 大幅扩展范围以适应真实数据
                'correlation_bands': ['theta']  # 相关波段
            },
            'theta': {
                'freq_range': (4, 8),     # Theta波段：4-8Hz
                'max_change_rate': 0.8,   # 最大变化率 (80%/sample) - 收紧以改善状态分析
                'physiological_range': (200, 15000),  # 收紧范围，过滤异常值
                'correlation_bands': ['delta', 'low_alpha', 'high_alpha']  # 相关波段
            },
            'low_alpha': {
                'freq_range': (8, 10),    # Low Alpha波段：8-10Hz
                'max_change_rate': 1.5,   # 最大变化率 (150%/sample) - 冷启动期更宽松
                'physiological_range': (0, 100000),  # 扩展范围以适应真实数据
                'correlation_bands': ['theta', 'high_alpha', 'low_beta']  # 相关波段
            },
            'high_alpha': {
                'freq_range': (10, 13),   # High Alpha波段：10-13Hz
                'max_change_rate': 1.5,   # 最大变化率 (150%/sample) - 冷启动期更宽松
                'physiological_range': (0, 100000),  # 扩展范围以适应真实数据
                'correlation_bands': ['low_alpha', 'theta', 'low_beta']  # 相关波段
            },
            'low_beta': {
                'freq_range': (13, 20),   # Low Beta波段：13-20Hz
                'max_change_rate': 1.5,   # 最大变化率 (150%/sample) - 冷启动期更宽松
                'physiological_range': (0, 50000),  # 扩展范围以适应真实数据
                'correlation_bands': ['high_alpha', 'high_beta', 'low_gamma']  # 相关波段
            },
            'high_beta': {
                'freq_range': (20, 30),   # High Beta波段：20-30Hz
                'max_change_rate': 1.5,   # 最大变化率 (150%/sample) - 冷启动期更宽松
                'physiological_range': (0, 50000),  # 扩展范围以适应真实数据
                'correlation_bands': ['low_beta', 'low_gamma', 'mid_gamma']  # 相关波段
            },
            'low_gamma': {
                'freq_range': (30, 40),   # Low Gamma波段：30-40Hz
                'max_change_rate': 1.5,   # 最大变化率 (150%/sample) - 冷启动期更宽松
                'physiological_range': (0, 30000),  # 扩展范围以适应真实数据
                'correlation_bands': ['high_beta', 'mid_gamma']  # 相关波段
            },
            'mid_gamma': {
                'freq_range': (40, 60),   # Mid Gamma波段：40-60Hz
                'max_change_rate': 1.5,   # 最大变化率 (150%/sample) - 冷启动期更宽松
                'physiological_range': (0, 20000),  # 扩展范围以适应真实数据
                'correlation_bands': ['low_gamma', 'high_beta']  # 相关波段
            },
            # 保持向后兼容的传统4频域配置 - 收紧阈值以改善状态分析
            'alpha': {
                'freq_range': (8, 13),    # 传统Alpha波段：8-13Hz
                'max_change_rate': 0.5,   # 最大变化率 (50%/sample) - 收紧阈值
                'physiological_range': (500, 6000),  # 收紧生理学范围，过滤异常高值
                'correlation_bands': ['theta', 'beta']  # 相关波段
            },
            'beta': {
                'freq_range': (13, 30),   # 传统Beta波段：13-30Hz
                'max_change_rate': 0.6,   # 最大变化率 (60%/sample) - 收紧阈值
                'physiological_range': (300, 5000),  # 收紧生理学范围，过滤异常高值
                'correlation_bands': ['alpha', 'gamma']  # 相关波段
            },
            'gamma': {
                'freq_range': (30, 100),  # 传统Gamma波段：30-100Hz
                'max_change_rate': 0.6,   # 最大变化率 (60%/sample) - 收紧阈值
                'physiological_range': (100, 3000),  # 收紧生理学范围，过滤异常高值
                'correlation_bands': ['beta']  # 相关波段
            }
        }
        
        # 历史数据存储
        self.signal_history = {band: deque(maxlen=window_size) for band in self.band_configs.keys()}
        self.raw_history = {band: deque(maxlen=window_size) for band in self.band_configs.keys()}
        self.timestamps = deque(maxlen=window_size)
        
        # 统计信息
        self.stats = {band: {'total': 0, 'filtered': 0, 'anomalies': []} for band in self.band_configs.keys()}
        
        # 自适应参数
        self.adaptive_thresholds = {band: {'mean': 0, 'std': 0, 'updated': False} for band in self.band_configs.keys()}
        
    def filter_signal(self, target_band: str, raw_value: int, context_signals: Dict[str, int] = None) -> Tuple[int, Dict]:
        """
        单波段信号过滤接口（兼容ThetaService调用）
        
        Args:
            target_band: 目标波段名称 (如 'theta')
            raw_value: 原始信号值
            context_signals: 上下文信号（其他波段的值）
            
        Returns:
            tuple: (过滤后的值, 分析结果字典)
        """
        # 构建多波段信号字典
        signals = {target_band: raw_value}
        if context_signals:
            signals.update(context_signals)
        
        # 调用多波段处理
        result = self.process_multi_band_signal(signals)
        
        # 提取目标波段的结果
        filtered_value = result['filtered_signals'].get(target_band, raw_value)
        
        # 构建兼容的返回格式
        analysis_result = {
            'filtered_value': filtered_value,
            'anomaly_detected': result['anomaly_flags'].get(target_band, False),
            'quality_score': result['quality_score'],
            'analysis_report': result['analysis_report']
        }
        
        return filtered_value, analysis_result
        
    def process_multi_band_signal(self, brain_wave_result) -> dict:
        """
        处理多波段脑电信号的高级过滤 - 8频域增强版本
        
        Args:
            brain_wave_result: BrainWaveResult对象或字典（支持8频域数据）
            
        Returns:
            dict: 过滤后的脑电数据结果字典
        """
        try:
            # 类型验证和自动转换
            if isinstance(brain_wave_result, dict):
                from response.BrainWaveResult import BrainWaveResult
                brain_wave_result = BrainWaveResult.from_dict(brain_wave_result)
                logger.debug("AdvancedSignalFilter: 自动将字典转换为BrainWaveResult对象")
            elif not hasattr(brain_wave_result, 'delta'):
                from exception.base_exceptions import FilterException
                raise FilterException(
                    f"AdvancedSignalFilter: 输入数据类型无效: {type(brain_wave_result)}",
                    filter_type="advanced_signal_filter_input_validation"
                )
            # 检测是否为8频域数据
            has_8bands = hasattr(brain_wave_result, 'low_alpha') and hasattr(brain_wave_result, 'high_alpha')
            
            if has_8bands:
                # 8频域增强处理
                processed_result = self._process_8bands_enhanced(brain_wave_result)
            else:
                # 传统4频域处理（向后兼容）
                processed_result = self._process_4bands_legacy(brain_wave_result)
            
            # 将BrainWaveResult对象转换为字典格式返回
            result_dict = processed_result.to_dict()
            
            # 添加处理信息
            if 'processing_info' not in result_dict:
                result_dict['processing_info'] = {}
            result_dict['processing_info']['advanced_signal_filter'] = {
                'status': 'processed',
                'bands_type': '8bands' if has_8bands else '4bands',
                'details': f'Advanced signal filtering applied with {"8" if has_8bands else "4"} frequency bands.'
            }
            
            return result_dict
                
        except Exception as e:
            filter_error = FilterException(
                f"高级信号过滤失败: {e}",
                filter_type="advanced_signal_filter"
            )
            global_exception_handler.handle_exception(filter_error)
            
            # 返回错误信息的字典格式
            if hasattr(brain_wave_result, 'to_dict'):
                error_dict = brain_wave_result.to_dict()
            elif isinstance(brain_wave_result, dict):
                error_dict = brain_wave_result.copy()
            else:
                error_dict = {}
            
            if 'processing_info' not in error_dict:
                error_dict['processing_info'] = {}
            error_dict['processing_info']['advanced_signal_filter'] = {
                'status': 'error',
                'error': f'处理失败 - {str(e)}'
            }
            
            return error_dict
    
    def _process_8bands_enhanced(self, brain_wave_result: BrainWaveResult) -> BrainWaveResult:
        """
        8频域增强处理方法
        
        利用8个细分频域进行更精确的信号过滤和异常检测：
        1. 更细粒度的频段分析
        2. 增强的跨频段相关性验证
        3. 基于8频域的自适应阈值调整
        4. 频段间边界效应处理
        """
        try:
            # 提取8频域信号值
            raw_signals = {
                'delta': brain_wave_result.delta,
                'theta': brain_wave_result.theta,
                'low_alpha': getattr(brain_wave_result, 'low_alpha', 0),
                'high_alpha': getattr(brain_wave_result, 'high_alpha', 0),
                'low_beta': getattr(brain_wave_result, 'low_beta', 0),
                'high_beta': getattr(brain_wave_result, 'high_beta', 0),
                'low_gamma': getattr(brain_wave_result, 'low_gamma', 0),
                'mid_gamma': getattr(brain_wave_result, 'mid_gamma', 0)
            }
            
            timestamp = brain_wave_result.timestamp if hasattr(brain_wave_result, 'timestamp') else len(self.timestamps) * (1.0 / self.sampling_rate)
            self.timestamps.append(timestamp)
            
            # 状态转换检测（在异常检测之前）
            self._detect_state_transition(raw_signals)
            
            # 第一步：8频域基础异常检测
            basic_filtered, anomaly_flags = self._detect_8bands_basic_anomaly(raw_signals)
            
            # 第二步：8频域增强相关性验证
            correlation_filtered = self._apply_8bands_correlation_filter(basic_filtered, anomaly_flags)
            
            # 第三步：8频域连续性检测
            continuity_filtered = self._apply_8bands_continuity_filter(correlation_filtered, anomaly_flags)
            
            # 第四步：8频域频域特征验证
            final_filtered = self._apply_8bands_frequency_domain_filter(continuity_filtered, anomaly_flags)
            
            # 第五步：频段边界效应处理
            boundary_corrected = self._apply_8bands_boundary_correction(final_filtered)
            
            # 更新历史记录
            for band_name, filtered_value in boundary_corrected.items():
                if band_name in self.signal_history:
                    self.signal_history[band_name].append(filtered_value)
            
            # 更新自适应阈值
            self._update_adaptive_thresholds(boundary_corrected)
            
            # 创建结果副本并更新过滤后的值
            result = brain_wave_result.copy()
            result.delta = boundary_corrected.get('delta', brain_wave_result.delta)
            result.theta = boundary_corrected.get('theta', brain_wave_result.theta)
            result.update_band('low_alpha', boundary_corrected.get('low_alpha', getattr(brain_wave_result, 'low_alpha', 0)))
            result.update_band('high_alpha', boundary_corrected.get('high_alpha', getattr(brain_wave_result, 'high_alpha', 0)))
            result.update_band('low_beta', boundary_corrected.get('low_beta', getattr(brain_wave_result, 'low_beta', 0)))
            result.update_band('high_beta', boundary_corrected.get('high_beta', getattr(brain_wave_result, 'high_beta', 0)))
            result.update_band('low_gamma', boundary_corrected.get('low_gamma', getattr(brain_wave_result, 'low_gamma', 0)))
            result.update_band('mid_gamma', boundary_corrected.get('mid_gamma', getattr(brain_wave_result, 'mid_gamma', 0)))
            
            # 计算传统频域值（向后兼容）
            result.alpha = int((boundary_corrected.get('low_alpha', 0) + boundary_corrected.get('high_alpha', 0)) / 2)
            result.beta = int((boundary_corrected.get('low_beta', 0) + boundary_corrected.get('high_beta', 0)) / 2)
            result.gamma = int((boundary_corrected.get('low_gamma', 0) + boundary_corrected.get('mid_gamma', 0)) / 2)
            
            # 添加处理步骤信息
            processing_info = f"AdvancedSignalFilter_8Bands: 异常检测({sum(anomaly_flags.values())}/{len(anomaly_flags)})"
            result.add_processing_step("AdvancedSignalFilter_8Bands", {
                "info": processing_info, 
                "anomalies": anomaly_flags,
                "8bands_processing": True,
                "boundary_corrections_applied": True
            })
            
            logger.info(f"8频域高级信号过滤完成 - Delta:{result.delta}, Theta:{result.theta}, LowAlpha:{getattr(result, 'low_alpha', 0)}, HighAlpha:{getattr(result, 'high_alpha', 0)}")
            return result
            
        except Exception as e:
            logger.error(f"8频域处理失败: {e}")
            return brain_wave_result
    
    def _process_4bands_legacy(self, brain_wave_result: BrainWaveResult) -> BrainWaveResult:
        """
        传统4频域处理方法（向后兼容）
        """
        try:
            # 提取各波段值
            raw_signals = {
                'theta': brain_wave_result.theta,
                'alpha': brain_wave_result.alpha,
                'beta': brain_wave_result.beta,
                'gamma': brain_wave_result.gamma
            }
            
            timestamp = brain_wave_result.timestamp if hasattr(brain_wave_result, 'timestamp') else len(self.timestamps) * (1.0 / self.sampling_rate)
            self.timestamps.append(timestamp)
            
            # 第一步：基础异常检测
            basic_filtered = {}
            anomaly_flags = {}
            
            for band_name, raw_value in raw_signals.items():
                if band_name in self.band_configs:
                    self.raw_history[band_name].append(raw_value)
                    self.stats[band_name]['total'] += 1
                    
                    # 基础异常检测
                    is_anomaly, filtered_value = self._detect_basic_anomaly(band_name, raw_value)
                    basic_filtered[band_name] = filtered_value
                    anomaly_flags[band_name] = is_anomaly
                    
                    if is_anomaly:
                        self.stats[band_name]['filtered'] += 1
            
            # 第二步：多波段相关性验证
            correlation_filtered = self._apply_correlation_filter(basic_filtered, anomaly_flags)
            
            # 第三步：信号连续性检测
            continuity_filtered = self._apply_continuity_filter(correlation_filtered, anomaly_flags)
            
            # 第四步：频域特征验证
            final_filtered = self._apply_frequency_domain_filter(continuity_filtered, anomaly_flags)
            
            # 更新历史记录
            for band_name, filtered_value in final_filtered.items():
                self.signal_history[band_name].append(filtered_value)
            
            # 更新自适应阈值
            self._update_adaptive_thresholds(final_filtered)
            
            # 创建结果副本并更新过滤后的值
            result = brain_wave_result.copy()
            result.theta = final_filtered.get('theta', brain_wave_result.theta)
            result.alpha = final_filtered.get('alpha', brain_wave_result.alpha)
            result.beta = final_filtered.get('beta', brain_wave_result.beta)
            result.gamma = final_filtered.get('gamma', brain_wave_result.gamma)
            
            # 添加处理步骤信息
            processing_info = f"AdvancedSignalFilter_Legacy: 异常检测({sum(anomaly_flags.values())}/{len(anomaly_flags)})"
            result.add_processing_step("AdvancedSignalFilter_Legacy", {"info": processing_info, "anomalies": anomaly_flags})
            
            logger.info(f"传统高级信号过滤完成 - Theta:{result.theta}, Alpha:{result.alpha}, Beta:{result.beta}, Gamma:{result.gamma}")
            return result
            
        except Exception as e:
            logger.error(f"传统4频域处理失败: {e}")
            return brain_wave_result
    
    def process_multi_band_signal_dict(self, raw_signals: Dict[str, int], timestamp: float = None) -> Dict[str, any]:
        """
        处理多波段脑电信号（字典格式，保持向后兼容）
        
        Args:
            raw_signals: 原始信号字典 {'theta': value, 'alpha': value, ...}
            timestamp: 时间戳
            
        Returns:
            dict: 处理结果包含过滤后的信号和详细分析
        """
        if timestamp is None:
            timestamp = len(self.timestamps) * (1.0 / self.sampling_rate)
        
        self.timestamps.append(timestamp)
        
        # 状态转换检测（在异常检测之前）
        self._detect_state_transition(raw_signals)
        
        # 第一步：基础异常检测
        basic_filtered = {}
        anomaly_flags = {}
        
        for band_name, raw_value in raw_signals.items():
            if band_name in self.band_configs:
                self.raw_history[band_name].append(raw_value)
                self.stats[band_name]['total'] += 1
                
                # 基础异常检测
                is_anomaly, filtered_value = self._detect_basic_anomaly(band_name, raw_value)
                basic_filtered[band_name] = filtered_value
                anomaly_flags[band_name] = is_anomaly
                
                if is_anomaly:
                    self.stats[band_name]['filtered'] += 1
        
        # 在状态转换期间跳过后续过滤步骤，避免过度过滤
        if self.state_transition_detector['in_transition']:
            logger.debug("状态转换期间：跳过相关性、连续性和频域过滤")
            final_filtered = basic_filtered
        else:
            # 第二步：多波段相关性验证
            correlation_filtered = self._apply_correlation_filter(basic_filtered, anomaly_flags)
            
            # 第三步：信号连续性检测
            continuity_filtered = self._apply_continuity_filter(correlation_filtered, anomaly_flags)
            
            # 第四步：频域特征验证
            final_filtered = self._apply_frequency_domain_filter(continuity_filtered, anomaly_flags)
        
        # 更新历史记录
        for band_name, filtered_value in final_filtered.items():
            self.signal_history[band_name].append(filtered_value)
        
        # 更新自适应阈值
        self._update_adaptive_thresholds(final_filtered)
        
        # 生成详细分析报告
        analysis_report = self._generate_analysis_report(raw_signals, final_filtered, anomaly_flags)
        
        return {
            'filtered_signals': final_filtered,
            'anomaly_flags': anomaly_flags,
            'analysis_report': analysis_report,
            'quality_score': self._calculate_signal_quality(final_filtered)
        }
    
    def _cold_start_validation(self, band_name: str, raw_value: int) -> Tuple[bool, int]:
        """
        冷启动期间的宽松验证
        
        在冷启动期间使用更宽松的验证标准：
        1. 只检查负值和超大值
        2. 不进行变化率检查
        3. 允许更大的生理学范围
        
        Args:
            band_name: 频段名称
            raw_value: 原始值
            
        Returns:
            Tuple[是否为异常, 替换值或原值]
        """
        if band_name not in self.band_configs:
            return False, raw_value
            
        config = self.band_configs[band_name]
        physiological_min, physiological_max = config['physiological_range']
        
        # 冷启动期间只检查极端异常
        if raw_value < 0:  # 负值检查
            return True, 0
        elif raw_value > physiological_max * 10:  # 超大值检查（10倍生理范围）
            return True, int(physiological_max * 0.5)
            
        return False, raw_value
    
    def _normal_operation_validation(self, band_name: str, raw_value: int) -> Tuple[bool, int]:
        """
        正常运行期间的完整验证
        
        包括所有验证检查：
        1. 生理学范围检查
        2. 变化率检查
        3. 统计学异常检测
        
        Args:
            band_name: 频段名称
            raw_value: 原始值
            
        Returns:
            Tuple[是否为异常, 替换值或原值]
        """
        if band_name not in self.band_configs:
            return False, raw_value
            
        config = self.band_configs[band_name]
        
        # 1. 生理学范围检查（状态转换期间放宽）
        min_range, max_range = config['physiological_range']
        if self.state_transition_detector['in_transition']:
            # 状态转换期间放宽生理学范围
            range_expansion = (max_range - min_range) * 2.0  # 放宽2倍
            min_range -= range_expansion
            max_range += range_expansion
            logger.debug(f"状态转换期 - {band_name}: 生理学范围放宽至 [{min_range:.0f}, {max_range:.0f}]")
        
        if raw_value < min_range or raw_value > max_range:
            return True, self._get_replacement_value(band_name, 'physiological_out_of_range')
        
        # 2. 极端值检测 (基于统计学)
        if len(self.signal_history[band_name]) >= 5:
            history_array = np.array(list(self.signal_history[band_name]))
            
            # 使用改进的Z-score检测
            modified_z_score = self._calculate_modified_z_score(raw_value, history_array)
            z_threshold = 3.5  # 更严格的阈值
            
            # 状态转换期间放宽统计学检测阈值
            if self.state_transition_detector['in_transition']:
                z_threshold *= 3.0  # 放宽3倍
                logger.debug(f"状态转换期 - {band_name}: Z-score {modified_z_score:.2f}, 放宽后阈值 {z_threshold:.2f}")
            
            if modified_z_score > z_threshold:
                return True, self._get_replacement_value(band_name, 'statistical_outlier')
        
        # 3. 变化率检测（考虑状态转换）
        if len(self.signal_history[band_name]) >= 1:
            last_value = self.signal_history[band_name][-1]
            if last_value > 0:
                change_rate = abs(raw_value - last_value) / last_value
                max_change_rate = config['max_change_rate']
                
                # 如果处于状态转换期，放宽阈值
                if self.state_transition_detector['in_transition']:
                    max_change_rate *= 20.0  # 转换期阈值放宽20倍
                    logger.debug(f"状态转换期 - {band_name}: 变化率 {change_rate:.2f}, 放宽后阈值 {max_change_rate:.2f}")
                
                if change_rate > max_change_rate:
                    return True, self._get_replacement_value(band_name, 'excessive_change_rate')
        
        return False, raw_value

    def _detect_state_transition(self, current_data: Dict[str, int]) -> bool:
        """
        检测状态转换
        
        Args:
            current_data: 当前频域数据字典
            
        Returns:
            bool: 是否处于状态转换期
        """
        detector = self.state_transition_detector
        
        # 计算当前数据的特征向量（使用主要频段的相对强度）
        current_pattern = [
            current_data.get('alpha', 0),
            current_data.get('beta', 0), 
            current_data.get('theta', 0),
            current_data.get('delta', 0)
        ]
        
        # 如果历史模式不足，直接添加当前模式
        if len(detector['recent_patterns']) < 3:
            detector['recent_patterns'].append(current_pattern)
            return False
            
        # 计算与最近模式的差异
        recent_avg = [sum(x) / len(detector['recent_patterns']) 
                     for x in zip(*detector['recent_patterns'])]
        
        # 计算欧几里得距离
        distance = sum((a - b) ** 2 for a, b in zip(current_pattern, recent_avg)) ** 0.5
        
        # 检测是否发生状态转换
        is_transition = distance > detector['transition_threshold']
        
        # 调试信息
        logger.debug(f"状态转换检测 - 距离: {distance:.2f}, 阈值: {detector['transition_threshold']}, 转换: {is_transition}")
        
        if is_transition:
            detector['in_transition'] = True
            detector['transition_counter'] = detector['transition_buffer_size']
            logger.info(f"检测到状态转换！距离: {distance:.2f}, 进入转换缓冲期")
        elif detector['transition_counter'] > 0:
            detector['transition_counter'] -= 1
            if detector['transition_counter'] == 0:
                detector['in_transition'] = False
                logger.info("状态转换缓冲期结束")
                
        # 更新历史模式
        detector['recent_patterns'].append(current_pattern)
        
        return detector['in_transition']
    
    def _detect_basic_anomaly(self, band_name: str, raw_value: int) -> Tuple[bool, int]:
        """
        基础异常检测（集成冷启动改进）
        
        检测单个频段的基础异常，根据冷启动状态选择验证方法：
        1. 冷启动期间：宽松验证
        2. 状态转换期间：使用冷启动验证（更宽松）
        3. 正常运行期间：完整验证
        
        Args:
            band_name: 频段名称
            raw_value: 原始信号值
            
        Returns:
            Tuple[是否为异常, 过滤后的值]
        """
        # 更新统计信息
        self.global_stats['total_processed'] += 1
        
        # 根据冷启动状态或状态转换状态选择验证方法
        if (self.cold_start_count < self.cold_start_threshold or 
            self.state_transition_detector['in_transition']):
            is_anomaly, processed_value = self._cold_start_validation(band_name, raw_value)
            if self.state_transition_detector['in_transition']:
                logger.debug(f"状态转换期 - {band_name}: 使用冷启动验证（宽松模式）")
        else:
            is_anomaly, processed_value = self._normal_operation_validation(band_name, raw_value)
        
        if is_anomaly:
            self.global_stats['anomalies_detected'] += 1
            self.global_stats['replacements_made'] += 1
        
        # 增加冷启动计数
        self.cold_start_count += 1
        
        return is_anomaly, processed_value
    
    def _calculate_modified_z_score(self, value: float, data_array: np.ndarray) -> float:
        """计算改进的Z-score，使用中位数绝对偏差(MAD)"""
        median = np.median(data_array)
        mad = np.median(np.abs(data_array - median))
        
        if mad == 0:
            return 0
        
        modified_z_score = 0.6745 * (value - median) / mad
        return abs(modified_z_score)
    
    def _apply_correlation_filter(self, signals: Dict[str, int], anomaly_flags: Dict[str, bool]) -> Dict[str, int]:
        """基于多波段相关性的过滤"""
        filtered_signals = signals.copy()
        
        # 检查各波段间的生理学相关性
        for band_name, value in signals.items():
            if not anomaly_flags[band_name]:  # 只对非异常信号进行相关性检查
                continue
                
            config = self.band_configs[band_name]
            correlation_score = 0
            valid_correlations = 0
            
            # 计算与相关波段的一致性
            for corr_band in config['correlation_bands']:
                if corr_band in signals and not anomaly_flags.get(corr_band, True):
                    correlation_score += self._calculate_band_correlation(band_name, corr_band, value, signals[corr_band])
                    valid_correlations += 1
            
            # 如果相关性检查通过，可能恢复该信号
            if valid_correlations > 0:
                avg_correlation = correlation_score / valid_correlations
                if avg_correlation > 0.7:  # 高相关性阈值
                    filtered_signals[band_name] = value
                    anomaly_flags[band_name] = False
        
        return filtered_signals
    
    def _calculate_band_correlation(self, band1: str, band2: str, value1: int, value2: int) -> float:
        """计算两个波段间的相关性得分"""
        # 基于生理学知识的相关性模型
        correlation_models = {
            ('theta', 'alpha'): lambda v1, v2: 1.0 - abs(v1/v2 - 0.8) if v2 > 0 else 0,  # Theta通常比Alpha稍低
            ('alpha', 'beta'): lambda v1, v2: 1.0 - abs(v1/v2 - 0.6) if v2 > 0 else 0,   # Alpha通常比Beta低
            ('beta', 'gamma'): lambda v1, v2: 1.0 - abs(v1/v2 - 2.0) if v2 > 0 else 0,  # Beta通常比Gamma高
        }
        
        key = (band1, band2) if (band1, band2) in correlation_models else (band2, band1)
        if key in correlation_models:
            return max(0, min(1, correlation_models[key](value1, value2)))
        
        return 0.5  # 默认中等相关性
    
    def _apply_continuity_filter(self, signals: Dict[str, int], anomaly_flags: Dict[str, bool]) -> Dict[str, int]:
        """基于信号连续性的过滤"""
        filtered_signals = signals.copy()
        
        for band_name, value in signals.items():
            if len(self.signal_history[band_name]) < 3:
                continue
            
            # 计算信号的连续性指标
            history = list(self.signal_history[band_name])[-3:]
            
            # 检查是否存在突然的跳跃
            gradients = np.diff(history + [value])
            
            # 如果梯度变化过大，认为是非连续信号
            if len(gradients) >= 2:
                gradient_change = abs(gradients[-1] - gradients[-2])
                avg_gradient = np.mean(np.abs(gradients[:-1]))
                
                if avg_gradient > 0 and gradient_change / avg_gradient > 2.0:
                    # 使用三次样条插值进行平滑
                    filtered_signals[band_name] = self._interpolate_smooth_value(band_name, history)
                    anomaly_flags[band_name] = True
        
        return filtered_signals
    
    def _apply_frequency_domain_filter(self, signals: Dict[str, int], anomaly_flags: Dict[str, bool]) -> Dict[str, int]:
        """基于频域特征的过滤"""
        filtered_signals = signals.copy()
        
        for band_name, value in signals.items():
            if len(self.signal_history[band_name]) < 10:  # 需要足够的数据进行频域分析
                continue
            
            # 构建时间序列
            time_series = list(self.signal_history[band_name]) + [value]
            
            # 计算功率谱密度
            try:
                freqs, psd = signal.periodogram(time_series, fs=self.sampling_rate)
                
                # 检查是否存在异常的频率成分
                config = self.band_configs[band_name]
                target_freq_range = config['freq_range']
                
                # 找到目标频率范围内的功率
                freq_mask = (freqs >= target_freq_range[0]) & (freqs <= target_freq_range[1])
                target_power = np.sum(psd[freq_mask])
                total_power = np.sum(psd)
                
                # 计算目标频段的功率占比
                power_ratio = target_power / total_power if total_power > 0 else 0
                
                # 如果目标频段功率占比过低，可能是噪声
                if power_ratio < 0.3:  # 阈值可调
                    filtered_signals[band_name] = self._get_replacement_value(band_name, 'frequency_domain_anomaly')
                    anomaly_flags[band_name] = True
                    
            except Exception as e:
                processing_error = SignalProcessingException(
                    f"频域分析失败 {band_name}: {e}",
                    signal_type="frequency_domain_analysis"
                )
                global_exception_handler.handle_exception(processing_error)
        
        return filtered_signals
    
    def _apply_historical_correction(self, brain_wave_result: BrainWaveResult) -> BrainWaveResult:
        """应用历史数据修正"""
        result = brain_wave_result.copy()
        
        # 使用历史数据的中位数作为修正值
        if len(self.signal_history['theta']) > 0:
            result.theta = int(np.median(list(self.signal_history['theta'])[-5:]))
        if len(self.signal_history['alpha']) > 0:
            result.alpha = int(np.median(list(self.signal_history['alpha'])[-5:]))
        if len(self.signal_history['beta']) > 0:
            result.beta = int(np.median(list(self.signal_history['beta'])[-5:]))
        if len(self.signal_history['gamma']) > 0:
            result.gamma = int(np.median(list(self.signal_history['gamma'])[-5:]))
            
        return result
    
    def _apply_correlation_correction(self, brain_wave_result: BrainWaveResult) -> BrainWaveResult:
        """应用相关性修正"""
        result = brain_wave_result.copy()
        
        # 基于生理学相关性进行修正
        alpha = 0.3  # 修正系数
        
        if len(self.signal_history['theta']) > 0:
            last_theta = self.signal_history['theta'][-1]
            result.theta = int(alpha * result.theta + (1 - alpha) * last_theta)
        if len(self.signal_history['alpha']) > 0:
            last_alpha = self.signal_history['alpha'][-1]
            result.alpha = int(alpha * result.alpha + (1 - alpha) * last_alpha)
        if len(self.signal_history['beta']) > 0:
            last_beta = self.signal_history['beta'][-1]
            result.beta = int(alpha * result.beta + (1 - alpha) * last_beta)
        if len(self.signal_history['gamma']) > 0:
            last_gamma = self.signal_history['gamma'][-1]
            result.gamma = int(alpha * result.gamma + (1 - alpha) * last_gamma)
        
        return result
    
    def _apply_continuity_smoothing(self, brain_wave_result: BrainWaveResult) -> BrainWaveResult:
        """应用连续性平滑"""
        result = brain_wave_result.copy()
        
        # 对各波段应用轻度平滑
        alpha = 0.3  # 平滑系数
        
        if len(self.signal_history['theta']) > 0:
            last_theta = self.signal_history['theta'][-1]
            result.theta = int(alpha * result.theta + (1 - alpha) * last_theta)
            
        if len(self.signal_history['alpha']) > 0:
            last_alpha = self.signal_history['alpha'][-1]
            result.alpha = int(alpha * result.alpha + (1 - alpha) * last_alpha)
            
        if len(self.signal_history['beta']) > 0:
            last_beta = self.signal_history['beta'][-1]
            result.beta = int(alpha * result.beta + (1 - alpha) * last_beta)
            
        if len(self.signal_history['gamma']) > 0:
            last_gamma = self.signal_history['gamma'][-1]
            result.gamma = int(alpha * result.gamma + (1 - alpha) * last_gamma)
        
        return result
    
    def _basic_anomaly_detection(self, theta: int, alpha: int, beta: int, gamma: int) -> bool:
        """基础异常检测"""
        # 检查是否在生理学合理范围内
        ranges = {
            'theta': self.band_configs['theta']['physiological_range'],
            'alpha': self.band_configs['alpha']['physiological_range'],
            'beta': self.band_configs['beta']['physiological_range'],
            'gamma': self.band_configs['gamma']['physiological_range']
        }
        
        values = {'theta': theta, 'alpha': alpha, 'beta': beta, 'gamma': gamma}
        
        for band, value in values.items():
            if value < ranges[band][0] or value > ranges[band][1]:
                return False
        
        return True
    
    def _validate_multi_band_correlation(self, theta: int, alpha: int, beta: int, gamma: int) -> bool:
        """验证多波段相关性"""
        # 简单的相关性检查
        if alpha == 0 or beta == 0 or gamma == 0:
            return False
        
        # 检查比例关系是否合理
        theta_alpha_ratio = theta / alpha if alpha > 0 else 0
        alpha_beta_ratio = alpha / beta if beta > 0 else 0
        beta_gamma_ratio = beta / gamma if gamma > 0 else 0
        
        # 基于生理学的合理比例范围
        if not (0.3 <= theta_alpha_ratio <= 2.0):
            return False
        if not (0.2 <= alpha_beta_ratio <= 1.5):
            return False
        if not (0.5 <= beta_gamma_ratio <= 3.0):
            return False
        
        return True
    
    def _detect_continuity_issues(self, theta: int, alpha: int, beta: int, gamma: int) -> list:
        """检测连续性问题"""
        issues = []
        
        values = {'theta': theta, 'alpha': alpha, 'beta': beta, 'gamma': gamma}
        
        for band, value in values.items():
            if len(self.signal_history[band]) > 0:
                last_value = self.signal_history[band][-1]
                if last_value > 0:
                    change_rate = abs(value - last_value) / last_value
                    if change_rate > self.band_configs[band]['max_change_rate']:
                        issues.append(f"{band}波段变化率过大: {change_rate:.2f}")
        
        return issues
    
    def _validate_frequency_features(self, theta: int, alpha: int, beta: int, gamma: int) -> bool:
        """验证频域特征"""
        # 简化的频域特征验证
        total_power = theta + alpha + beta + gamma
        if total_power == 0:
            return False
        
        # 计算各波段的相对功率
        theta_ratio = theta / total_power
        alpha_ratio = alpha / total_power
        beta_ratio = beta / total_power
        gamma_ratio = gamma / total_power
        
        # 检查是否在合理范围内
        if not (0.1 <= theta_ratio <= 0.6):
            return False
        if not (0.1 <= alpha_ratio <= 0.5):
            return False
        if not (0.1 <= beta_ratio <= 0.4):
            return False
        if not (0.05 <= gamma_ratio <= 0.3):
            return False
        
        return True
    
    def _advanced_filter_theta(self, theta: int) -> int:
        """Theta波段的高级滤波"""
        return self.filter_signal(theta, 'theta')
    
    def _advanced_filter_alpha(self, alpha: int) -> int:
        """Alpha波段的高级滤波"""
        return self.filter_signal(alpha, 'alpha')
    
    def _advanced_filter_beta(self, beta: int) -> int:
        """Beta波段的高级滤波"""
        return self.filter_signal(beta, 'beta')
    
    def _advanced_filter_gamma(self, gamma: int) -> int:
        """Gamma波段的高级滤波"""
        return self.filter_signal(gamma, 'gamma')
    
    def _update_history(self, theta: int, alpha: int, beta: int, gamma: int):
        """更新历史记录"""
        self.signal_history['theta'].append(theta)
        self.signal_history['alpha'].append(alpha)
        self.signal_history['beta'].append(beta)
        self.signal_history['gamma'].append(gamma)
    
    def _get_replacement_value(self, band_name: str, anomaly_type: str) -> int:
        """获取替换值"""
        if len(self.signal_history[band_name]) == 0:
            # 使用生理学范围的中位数
            config = self.band_configs[band_name]
            return int(np.mean(config['physiological_range']))
        
        # 使用历史数据的中位数
        history_array = np.array(list(self.signal_history[band_name]))
        
        if anomaly_type == 'statistical_outlier':
            return int(np.median(history_array))
        elif anomaly_type == 'excessive_change_rate':
            # 使用指数移动平均
            return int(np.mean(history_array[-3:]) if len(history_array) >= 3 else np.mean(history_array))
        else:
            return int(np.median(history_array))
    
    def _interpolate_smooth_value(self, band_name: str, history: List[int]) -> int:
        """使用插值方法生成平滑值"""
        if len(history) < 2:
            return history[-1] if history else 0
        
        # 简单的线性预测
        x = np.arange(len(history))
        y = np.array(history)
        
        # 使用最后几个点进行线性拟合
        if len(history) >= 3:
            coeffs = np.polyfit(x[-3:], y[-3:], 1)
            predicted = int(coeffs[0] * len(history) + coeffs[1])
        else:
            predicted = int(y[-1] + (y[-1] - y[-2]) * 0.5)  # 简单外推
        
        # 确保预测值在合理范围内
        config = self.band_configs[band_name]
        return max(config['physiological_range'][0], 
                  min(predicted, config['physiological_range'][1]))
    
    def _update_adaptive_thresholds(self, signals: Dict[str, int]):
        """更新自适应阈值"""
        for band_name, value in signals.items():
            if len(self.signal_history[band_name]) >= 10:
                history_array = np.array(list(self.signal_history[band_name]))
                self.adaptive_thresholds[band_name]['mean'] = np.mean(history_array)
                self.adaptive_thresholds[band_name]['std'] = np.std(history_array)
                self.adaptive_thresholds[band_name]['updated'] = True
    
    def _calculate_signal_quality(self, signals: Dict[str, int]) -> float:
        """计算信号质量得分"""
        quality_scores = []
        
        for band_name, value in signals.items():
            config = self.band_configs[band_name]
            
            # 基于生理学范围的得分
            range_score = 1.0 - abs(value - np.mean(config['physiological_range'])) / (config['physiological_range'][1] - config['physiological_range'][0])
            range_score = max(0, min(1, range_score))
            
            # 基于稳定性的得分
            if len(self.signal_history[band_name]) >= 5:
                recent_values = list(self.signal_history[band_name])[-5:]
                stability_score = 1.0 / (1.0 + np.std(recent_values) / np.mean(recent_values))
            else:
                stability_score = 0.5
            
            # 综合得分
            band_quality = (range_score * 0.6 + stability_score * 0.4)
            quality_scores.append(band_quality)
        
        return np.mean(quality_scores) if quality_scores else 0.0
    
    def _generate_analysis_report(self, raw_signals: Dict[str, int], filtered_signals: Dict[str, int], 
                                anomaly_flags: Dict[str, bool]) -> Dict[str, any]:
        """生成详细的分析报告"""
        report = {
            'timestamp': self.timestamps[-1] if self.timestamps else 0,
            'signal_analysis': {},
            'overall_quality': self._calculate_signal_quality(filtered_signals),
            'anomaly_summary': {
                'total_bands': len(raw_signals),
                'anomalous_bands': sum(anomaly_flags.values()),
                'anomaly_rate': sum(anomaly_flags.values()) / len(raw_signals) if raw_signals else 0
            }
        }
        
        for band_name in raw_signals.keys():
            if band_name in self.band_configs:
                band_report = {
                    'raw_value': raw_signals[band_name],
                    'filtered_value': filtered_signals.get(band_name, raw_signals[band_name]),
                    'is_anomaly': anomaly_flags.get(band_name, False),
                    'filter_efficiency': self.stats[band_name]['filtered'] / self.stats[band_name]['total'] if self.stats[band_name]['total'] > 0 else 0,
                    'physiological_state': self._assess_physiological_state(band_name, filtered_signals.get(band_name, 0))
                }
                report['signal_analysis'][band_name] = band_report
        
        return report
    
    def _assess_physiological_state(self, band_name: str, value: int) -> str:
        """评估生理状态"""
        config = self.band_configs[band_name]
        range_min, range_max = config['physiological_range']
        
        # 标准化值
        normalized = (value - range_min) / (range_max - range_min)
        
        if band_name == 'theta':
            if normalized < 0.3:
                return "低Theta - 清醒专注"
            elif normalized < 0.7:
                return "正常Theta - 放松状态"
            else:
                return "高Theta - 深度放松/困倦"
        elif band_name == 'alpha':
            if normalized < 0.3:
                return "低Alpha - 紧张/专注"
            elif normalized < 0.7:
                return "正常Alpha - 平静清醒"
            else:
                return "高Alpha - 深度放松"
        elif band_name == 'beta':
            if normalized < 0.3:
                return "低Beta - 困倦状态"
            elif normalized < 0.7:
                return "正常Beta - 正常清醒"
            else:
                return "高Beta - 高度专注/焦虑"
        elif band_name == 'gamma':
            if normalized < 0.3:
                return "低Gamma - 低认知活动"
            elif normalized < 0.7:
                return "正常Gamma - 正常认知"
            else:
                return "高Gamma - 高认知/学习状态"
        
        return "未知状态"
    
    def get_filter_statistics(self) -> Dict[str, any]:
        """获取过滤器统计信息"""
        stats_summary = {}
        
        for band_name, stats in self.stats.items():
            if stats['total'] > 0:
                stats_summary[band_name] = {
                    'total_samples': stats['total'],
                    'filtered_samples': stats['filtered'],
                    'filter_rate': stats['filtered'] / stats['total'],
                    'current_threshold': self.adaptive_thresholds[band_name]
                }
        
        return stats_summary
    
    def reset_filter(self):
        """重置过滤器状态"""
        for band in self.band_configs.keys():
            self.signal_history[band].clear()
            self.raw_history[band].clear()
            self.stats[band] = {'total': 0, 'filtered': 0, 'anomalies': []}
            self.adaptive_thresholds[band] = {'mean': 0, 'std': 0, 'updated': False}
        
        self.timestamps.clear()
        logger.info("高级信号过滤器已重置")
    
    def _detect_8bands_basic_anomaly(self, raw_signals: Dict[str, int]) -> Tuple[Dict[str, int], Dict[str, bool]]:
        """
        8频域基础异常检测
        
        对8个频域分别进行基础异常检测，包括：
        1. 生理学范围检查
        2. 统计学异常检测
        3. 变化率检查
        """
        basic_filtered = {}
        anomaly_flags = {}
        
        for band_name, raw_value in raw_signals.items():
            if band_name in self.band_configs:
                # 更新历史记录
                if band_name not in self.raw_history:
                    self.raw_history[band_name] = deque(maxlen=self.window_size)
                if band_name not in self.stats:
                    self.stats[band_name] = {'total': 0, 'filtered': 0, 'anomalies': []}
                
                self.raw_history[band_name].append(raw_value)
                self.stats[band_name]['total'] += 1
                
                # 确保全局统计信息存在
                if 'total_processed' not in self.stats:
                    self.stats['total_processed'] = 0
                if 'anomalies_detected' not in self.stats:
                    self.stats['anomalies_detected'] = 0
                if 'replacements_made' not in self.stats:
                    self.stats['replacements_made'] = 0
                
                # 基础异常检测
                is_anomaly, filtered_value = self._detect_basic_anomaly(band_name, raw_value)
                basic_filtered[band_name] = filtered_value
                anomaly_flags[band_name] = is_anomaly
                
                if is_anomaly:
                    self.stats[band_name]['filtered'] += 1
        
        return basic_filtered, anomaly_flags
    
    def _apply_8bands_correlation_filter(self, signals: Dict[str, int], anomaly_flags: Dict[str, bool]) -> Dict[str, int]:
        """
        8频域增强相关性过滤
        
        利用8个频域间的相关性进行交叉验证：
        1. 相邻频段相关性检查
        2. 频段组合相关性验证
        3. 基于相关性的异常修正
        """
        correlation_filtered = signals.copy()
        
        # 定义相邻频段对
        adjacent_pairs = [
            ('delta', 'theta'),
            ('theta', 'low_alpha'),
            ('low_alpha', 'high_alpha'),
            ('high_alpha', 'low_beta'),
            ('low_beta', 'high_beta'),
            ('high_beta', 'low_gamma'),
            ('low_gamma', 'mid_gamma')
        ]
        
        for band1, band2 in adjacent_pairs:
            if band1 in signals and band2 in signals:
                # 计算相邻频段相关性
                correlation = self._calculate_8bands_correlation(band1, band2, signals[band1], signals[band2])
                
                # 如果相关性异常，进行修正
                if correlation < 0.3:  # 相关性阈值
                    if anomaly_flags.get(band1, False) and not anomaly_flags.get(band2, False):
                        # band1异常，用band2修正
                        correlation_filtered[band1] = self._estimate_from_neighbor(band1, band2, signals[band2])
                    elif anomaly_flags.get(band2, False) and not anomaly_flags.get(band1, False):
                        # band2异常，用band1修正
                        correlation_filtered[band2] = self._estimate_from_neighbor(band2, band1, signals[band1])
        
        return correlation_filtered
    
    def _apply_8bands_continuity_filter(self, signals: Dict[str, int], anomaly_flags: Dict[str, bool]) -> Dict[str, int]:
        """
        8频域连续性过滤
        
        检查8个频域的时间连续性：
        1. 单频段连续性检查
        2. 跨频段连续性验证
        3. 基于连续性的平滑处理
        """
        continuity_filtered = signals.copy()
        
        for band_name, value in signals.items():
            if band_name in self.signal_history and len(self.signal_history[band_name]) >= 2:
                # 检查连续性
                recent_values = list(self.signal_history[band_name])[-2:]
                if self._check_8bands_continuity(band_name, value, recent_values):
                    # 连续性正常，保持原值
                    continue
                else:
                    # 连续性异常，应用平滑处理
                    continuity_filtered[band_name] = self._apply_8bands_smoothing(band_name, value, recent_values)
        
        return continuity_filtered
    
    def _apply_8bands_frequency_domain_filter(self, signals: Dict[str, int], anomaly_flags: Dict[str, bool]) -> Dict[str, int]:
        """
        8频域频域特征过滤
        
        基于频域特征进行过滤：
        1. 频段功率分布检查
        2. 频段间功率比例验证
        3. 频域特征异常修正
        """
        frequency_filtered = signals.copy()
        
        # 检查频段功率分布的合理性
        total_power = sum(signals.values())
        if total_power > 0:
            for band_name, value in signals.items():
                power_ratio = value / total_power
                expected_ratio = self._get_expected_power_ratio(band_name)
                
                # 如果功率比例异常，进行修正
                if abs(power_ratio - expected_ratio) > 0.3:  # 阈值可调
                    frequency_filtered[band_name] = int(total_power * expected_ratio)
        
        return frequency_filtered
    
    def _apply_8bands_boundary_correction(self, signals: Dict[str, int]) -> Dict[str, int]:
        """
        8频域边界效应修正
        
        处理相邻频段间的边界效应：
        1. 频段边界平滑
        2. 重叠频率处理
        3. 频段间能量守恒
        """
        boundary_corrected = signals.copy()
        
        # 定义边界修正对
        boundary_pairs = [
            ('delta', 'theta', 4),      # 4Hz边界
            ('theta', 'low_alpha', 8),  # 8Hz边界
            ('low_alpha', 'high_alpha', 10),  # 10Hz边界
            ('high_alpha', 'low_beta', 13),   # 13Hz边界
            ('low_beta', 'high_beta', 20),    # 20Hz边界
            ('high_beta', 'low_gamma', 30),   # 30Hz边界
            ('low_gamma', 'mid_gamma', 50)    # 50Hz边界
        ]
        
        for band1, band2, boundary_freq in boundary_pairs:
            if band1 in signals and band2 in signals:
                # 应用边界平滑
                corrected_values = self._apply_boundary_smoothing(band1, band2, signals[band1], signals[band2], boundary_freq)
                boundary_corrected[band1] = corrected_values[0]
                boundary_corrected[band2] = corrected_values[1]
        
        return boundary_corrected
    
    def _calculate_8bands_correlation(self, band1: str, band2: str, value1: int, value2: int) -> float:
        """计算8频域相关性"""
        try:
            if band1 in self.signal_history and band2 in self.signal_history:
                history1 = list(self.signal_history[band1]) + [value1]
                history2 = list(self.signal_history[band2]) + [value2]
                
                if len(history1) >= 3 and len(history2) >= 3:
                    correlation = np.corrcoef(history1, history2)[0, 1]
                    return abs(correlation) if not np.isnan(correlation) else 0.5
            return 0.5  # 默认中等相关性
        except Exception:
            return 0.5
    
    def _estimate_from_neighbor(self, target_band: str, neighbor_band: str, neighbor_value: int) -> int:
        """基于相邻频段估算目标频段值"""
        try:
            # 基于频段特性的估算系数
            estimation_factors = {
                ('delta', 'theta'): 1.2,
                ('theta', 'delta'): 0.8,
                ('theta', 'low_alpha'): 0.9,
                ('low_alpha', 'theta'): 1.1,
                ('low_alpha', 'high_alpha'): 1.0,
                ('high_alpha', 'low_alpha'): 1.0,
                ('high_alpha', 'low_beta'): 0.8,
                ('low_beta', 'high_alpha'): 1.2,
                ('low_beta', 'high_beta'): 1.0,
                ('high_beta', 'low_beta'): 1.0,
                ('high_beta', 'low_gamma'): 0.7,
                ('low_gamma', 'high_beta'): 1.4,
                ('low_gamma', 'mid_gamma'): 1.1,
                ('mid_gamma', 'low_gamma'): 0.9
            }
            
            factor = estimation_factors.get((target_band, neighbor_band), 1.0)
            estimated_value = int(neighbor_value * factor)
            
            # 确保在生理学合理范围内
            if target_band in self.band_configs:
                min_val, max_val = self.band_configs[target_band]['physiological_range']
                estimated_value = max(min_val, min(estimated_value, max_val))
            
            return estimated_value
        except Exception:
            return neighbor_value
    
    def _check_8bands_continuity(self, band_name: str, current_value: int, recent_values: List[int]) -> bool:
        """检查8频域连续性"""
        try:
            if not recent_values:
                return True
            
            last_value = recent_values[-1]
            if last_value == 0:
                return True
            
            change_rate = abs(current_value - last_value) / last_value
            max_change_rate = self.band_configs.get(band_name, {}).get('max_change_rate', 0.5)
            
            return change_rate <= max_change_rate
        except Exception:
            return True
    
    def _apply_8bands_smoothing(self, band_name: str, current_value: int, recent_values: List[int]) -> int:
        """应用8频域平滑处理"""
        try:
            if not recent_values:
                return current_value
            
            # 使用加权平均进行平滑
            weights = [0.5, 0.3, 0.2]  # 当前值、上一个值、上上个值的权重
            values = [current_value] + recent_values[-2:]
            
            weighted_sum = sum(w * v for w, v in zip(weights[:len(values)], values))
            weight_sum = sum(weights[:len(values)])
            
            smoothed_value = int(weighted_sum / weight_sum)
            
            # 确保在生理学合理范围内
            if band_name in self.band_configs:
                min_val, max_val = self.band_configs[band_name]['physiological_range']
                smoothed_value = max(min_val, min(smoothed_value, max_val))
            
            return smoothed_value
        except Exception:
            return current_value
    
    def _get_expected_power_ratio(self, band_name: str) -> float:
        """获取期望的功率比例"""
        # 基于脑电生理学的典型功率分布
        expected_ratios = {
            'delta': 0.25,      # Delta通常占25%
            'theta': 0.20,      # Theta通常占20%
            'low_alpha': 0.15,  # Low Alpha通常占15%
            'high_alpha': 0.15, # High Alpha通常占15%
            'low_beta': 0.10,   # Low Beta通常占10%
            'high_beta': 0.08,  # High Beta通常占8%
            'low_gamma': 0.04,  # Low Gamma通常占4%
            'mid_gamma': 0.03   # Mid Gamma通常占3%
        }
        return expected_ratios.get(band_name, 0.1)
    
    def _apply_boundary_smoothing(self, band1: str, band2: str, value1: int, value2: int, boundary_freq: float) -> Tuple[int, int]:
        """应用边界平滑处理"""
        try:
            # 简单的边界平滑：确保相邻频段值的平滑过渡
            if abs(value1 - value2) > max(value1, value2) * 0.5:  # 如果差异过大
                # 应用平滑处理
                avg_value = (value1 + value2) // 2
                smoothed_value1 = int(value1 * 0.7 + avg_value * 0.3)
                smoothed_value2 = int(value2 * 0.7 + avg_value * 0.3)
                return smoothed_value1, smoothed_value2
            else:
                return value1, value2
        except Exception:
            return value1, value2
    
    def filter_session(self, band_data: Dict[str, List[float]]):
        """批量处理整段睡眠信号，返回过滤结果及报告"""
        results, reports = {}, {}
        for band, series in band_data.items():
            filtered = [self.filter_signal(band, v) for v in series]
            results[band] = filtered
        report = self._generate_analysis_report()
        return results, report